/**
 * =========================================
 *
 * Koa 操作 MySQL 数据库
 *
 * 		插入数据
 * 			INSERT INTO <表名> (字段,字段) value ('value', 'value')
 *
 * 	    修改数据
 * 	    	update <表名> set username='zhangsan',password='123456' where id=1
 *
 * 	     删除数据
 * 	     	delete from <表名> where id=3
 *
 * 	     查询数据
 * 	     	select * from <表名> where username='zhangsan'
 *
 * =========================================
 */

const Koa = require('koa');
const router = require('koa-router')();
const path = require('path');
const koaTemplate = require('koa-art-template');
const DB = require('./module/db.js');
const app = new Koa();


// 配置模板引擎
koaTemplate(app, {
	root: path.join(__dirname, 'views'),
	extname: '.html',
	debug: process.env.NODE_ENV !== 'production'
});

router.get('/', async (ctx) => {

	let result = await DB.query('select * from user');
	ctx.render('index', {
		list: result
	});
});

router.get('/add', async (ctx) => {

	//let result = await DB.query('insert into user (username, password) value ("zhangsan", "123456")');
	let username = 'lisi';
	let password = '123456';
	let result = await DB.query('insert into user (username, password) value (?,?)', [username, password]);
	ctx.redirect('/');
});

router.get('/edit', async (ctx) => {

	let id = 3;
	let username = 'lisi';
	let password = '666666';
	let result = await DB.query('update user set username=?,password=? where id=?', [username, password, id]);
	ctx.redirect('/');
});

router.get('/del', async (ctx) => {

	let id = 3;
	let result = await DB.query('delete from user where id=?', [id]);
	ctx.redirect('/');
});


app.use(router.routes());
app.use(router.allowedMethods());
app.listen(8088);
console.log('Server run http://localhost:8088/');